package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.EmojiFilter;
import com.asktgapp.JGTool.JGColor;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.base.IndustryCommentDetailVO;
import com.asktgapp.model.FreeAskDetailVO;
import com.asktgapp.model.FreeAskSearchVO;
import com.asktgapp.model.IndustryInfoDetailVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.PhotoViewActivity;
import com.asktgapp.user.activity.ShareActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018-7-21 21:17:13
 * Description:维修常识 评论回复页面
 */

public class IndustryCommentFragment extends BaseFragment {
    private TextView myBack, myToolbarTitle, commit, tvAskName, tvTotalZan, addTime, tv_answer,toUserName,complaintNumber;
    private RecyclerView mRecyclerView;
    private BaseAdapter mBaseAdapter;
    private ImageView tvShare, tvZan, ivZan,ivHead, ivQuestionImg1, ivQuestionImg2, ivQuestionImg3;
    private EditText etComment;
    private String id, toUserId,mQuestionId,zanTemp;
    private LinearLayout llQuestionImg;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_free_ask_comment, container, false);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    private void setUI(IndustryInfoDetailVO.InformationCommentListBean bean) {
        if(bean==null)
            return;

        mQuestionId = bean.getInformationId();
        tvTotalZan.setText(String.valueOf(bean.getLikeNum()));
        if (TextUtils.isEmpty(bean.getLikeId())) {
            tvZan.setImageResource(R.mipmap.zan_2);
            ivZan.setImageResource(R.mipmap.zan_2);
            zanTemp = "1";
        } else {
            zanTemp = "0";
            tvZan.setImageResource(R.mipmap.zan_1);
            ivZan.setImageResource(R.mipmap.zan_1);
        }
        Date date = Util.StrToDate(bean.getAddTime(), "yyyy.MM.dd HH:mm:ss");
        String timeStr = Utils.getAskTime(date);
        addTime.setText(timeStr);
        tv_answer.setText(bean.getContent());
        llQuestionImg.setVisibility(View.GONE);
        toUserId = String.valueOf(bean.getUserId());

    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().getToolbar().setVisibility(View.GONE);
        id = getActivity().getIntent().getStringExtra("id");
        IndustryInfoDetailVO.InformationCommentListBean bean = (IndustryInfoDetailVO.InformationCommentListBean) getActivity().getIntent().getSerializableExtra("comment");

        myBack = rootView.findViewById(R.id.myBack);
        myToolbarTitle = rootView.findViewById(R.id.myToolbarTitle);
        mRecyclerView = rootView.findViewById(R.id.recycleHot);
        commit = rootView.findViewById(R.id.commit);
        tvShare = rootView.findViewById(R.id.tvShare);
        tvZan = rootView.findViewById(R.id.tvZan);
        ivZan = rootView.findViewById(R.id.ivZan);
        complaintNumber = rootView.findViewById(R.id.complaintNumber);
        etComment = rootView.findViewById(R.id.etComment);
        etComment.setFilters(new InputFilter[]{new EmojiFilter()});
        tvAskName = rootView.findViewById(R.id.tvAskName);
        tvTotalZan = rootView.findViewById(R.id.tvTotalZan);
        addTime = rootView.findViewById(R.id.addTime);
        ivHead = rootView.findViewById(R.id.iv_head_ask);
        tv_answer = rootView.findViewById(R.id.tv_answer);
        toUserName = rootView.findViewById(R.id.toUserName);
        llQuestionImg = rootView.findViewById(R.id.llQuestionImg);
        ivQuestionImg1 = rootView.findViewById(R.id.ivQuestionImg1);
        ivQuestionImg2 = rootView.findViewById(R.id.ivQuestionImg2);
        ivQuestionImg3 = rootView.findViewById(R.id.ivQuestionImg3);


        myBack.setOnClickListener(this);
        commit.setOnClickListener(this);
        tvShare.setOnClickListener(this);
        tvZan.setOnClickListener(this);
        ivZan.setOnClickListener(this);
        ivQuestionImg1.setOnClickListener(this);
        ivQuestionImg2.setOnClickListener(this);
        ivQuestionImg3.setOnClickListener(this);
        tv_answer.setOnClickListener(this);

        etComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    commit.setVisibility(View.VISIBLE);
                } else {
                    commit.setVisibility(View.GONE);
                }
            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.addItemDecoration(new DefaultItemDecoration(JGColor.APP_BACKGROUND));

        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_free_ask_comment, parent, false),
                        new BaseViewHolder.Callbacks() {
                            @Override
                            public void bind(BaseViewHolder holder, Object data) {
                                //文章标题
                                TextView allAnswer = holder.getView(R.id.allAnswer);
                                ImageView ivZan = holder.getView(R.id.ivZan);
                                ImageView ivAskHead = holder.getView(R.id.iv_head_ask);
                                if (data instanceof FreeAskSearchVO.DiscussBean) {
                                    final FreeAskSearchVO.DiscussBean bean = (FreeAskSearchVO.DiscussBean) data;
                                    ImageDisplayUtil.loadCircleHeadImage(getActivity(), ivAskHead, bean.getUserPic1());
                                    Date date = Util.StrToDate(bean.getDiscussAddTime(), "yyyy.MM.dd HH:mm:ss");
                                    String timeStr = Utils.getAskTime(date);
                                    holder.setText(R.id.addTime, timeStr);
                                    holder.setText(R.id.tv_answer, bean.getDiscussContent());
                                    holder.setText(R.id.tvAskName, bean.getUsername1());
                                    holder.setText(R.id.tvZan, bean.getDiscussLikeNum());

                                    if (TextUtils.isEmpty(bean.getLikeId()))
                                        ivZan.setImageResource(R.mipmap.zan_2);
                                    else {
                                        ivZan.setImageResource(R.mipmap.zan_1);
                                    }



                                    holder.getView(R.id.ivZan).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            //点赞接口
                                            if (TextUtils.isEmpty(bean.getLikeId())) {
                                                dealZan(bean.getDiscussId(), "1", 5);
                                            } else {
                                                dealZan(bean.getDiscussId(), "0", 5);
                                            }
                                        }
                                    });
                                }
                            }

                            @Override
                            public void onItemClick(View view, int position) {
//                                FreeAskSearchVO.DiscussBean answerListBean = (FreeAskSearchVO.DiscussBean) mBaseAdapter.getData(position);
//                                toUserName.setText("回复" + answerListBean.getUsername1() + "：");
                            }
                        });


                return holder;
            }
        };
        mRecyclerView.setAdapter(mBaseAdapter);


//        setUI(bean);
        if(bean!=null){
            ImageDisplayUtil.loadCircleHeadImage(getContext(),ivHead,bean.getUserPic1());
            tvAskName.setText(bean.getUsername1());
            setUI(bean);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tvShare:
                if(TextUtils.isEmpty(mQuestionId)){
                    showTost("资讯ID错误",0);
                    return;
                }
                Intent intent = new Intent(getActivity(), ShareActivity.class);
                intent.putExtra("type", 4);
                intent.putExtra("id", mQuestionId);
                startActivity(intent);
                break;
            case R.id.myBack:
                getActivity().onBackPressed();
                break;
            case R.id.tvZan:
                dealZan(id, zanTemp, 4);
                break;
            case R.id.ivZan:
                dealZan(id, zanTemp, 4);
                break;
            case R.id.commit:
                addDiscuss();
                break;
            case R.id.ivQuestionImg1:
                PhotoViewActivity.statr(getActivity(), 0, images);
                break;
            case R.id.ivQuestionImg2:
                PhotoViewActivity.statr(getActivity(), 1, images);
                break;
            case R.id.ivQuestionImg3:
                PhotoViewActivity.statr(getActivity(), 2, images);
                break;
            case R.id.tv_answer:
                toUserName.setText("");
                break;
        }
    }

    @Override
    public void loadData() {
        selAnswerDetail();
    }

    ArrayList<String> images;

    private void selAnswerDetail() {
        //                    deviceId	string	是
//                    platform	int	是
//                    page	int	是
//                    content	string	否	搜索的文字
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        ApiUtil.putDefultData(getActivity(), params);
        params.put("userId", PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID));
        params.put("platform", "0");
        params.put("deviceId", Utils.getDeviceId(MyApplication.getInstance()));
        params.put("page", 1);
        params.put("id", id);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<IndustryCommentDetailVO>> call = apiservice.selInformationCommentDetail(params);
        call.enqueue(new Callback<ApiResponseBody<IndustryCommentDetailVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<IndustryCommentDetailVO>> call, Response<ApiResponseBody<IndustryCommentDetailVO>> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    IndustryCommentDetailVO bean = response.body().getResult();

                    if (bean != null && bean.getDiscussList().size() > 0) {

                        mBaseAdapter.setData(bean.getDiscussList());
                        myToolbarTitle.setText(bean.getDiscussList().size() + "条回复");
                        complaintNumber.setText(bean.getDiscussList().size() + "回复");
                        mQuestionId = bean.getInformationCommentDetail().getInformationId();
                    }
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<IndustryCommentDetailVO>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }
    //回复评论
    private void addDiscuss() {
        if (Util.isEmpty(PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID))) {
            showTost("未登录！请先登录", 1);
            return;
        }
        String answer = etComment.getText().toString().trim();
        if (Util.isEmpty(answer)) {
            showTost("请输入您的评论", 1);
            return;
        }
        if (answer.length() > 500) {
            showTost("请将评论控制在500字内，当前字数：" + answer.length(), 1);
            return;
        }
        if (!Utils.noContainsEmoji(answer)) {
            showTost("不支持输入emoji表情", 1);
            return;
        }
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("commentId", id);
        params.put("content",toUserName.getText()+answer);
        params.put("userId", PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID));
        params.put("platform", "0");
        params.put("deviceId", Utils.getDeviceId(MyApplication.getInstance()));
        params.put("page", 1);
        params.put("toUserId", toUserId);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.insertInfoDiscuss(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    showTost("提交成功", 0);
                    commit.setVisibility(View.GONE);
                    getBaseActivity().hideSoftKeybord();
                    toUserName.setText("");
                    etComment.setText("");
                    selAnswerDetail();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    //评论
//    private void addDiscuss() {
//        String answer = etComment.getText().toString().trim();
//        answer  = toUserName.getText().toString()+answer;
//        if (Util.isEmpty(answer)) {
//            showTost("请输入您的评论", 1);
//            return;
//        }
//        if (answer.length() > 500) {
//            showTost("请将评论控制在500字内，当前字数：" + answer.length(), 1);
//            return;
//        }
//        if (!Utils.noContainsEmoji(answer)) {
//            showTost("不支持输入emoji表情", 1);
//            return;
//        }
//        Apiservice apiservice = ApiUtil.getInstance().create();
//        HashMap params = new HashMap();
//        params.put("id", id);
//        params.put("discussContent", answer);
//        params.put("userId", PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID));
//        params.put("platform", "0");
//        params.put("deviceId", Utils.getDeviceId(MyApplication.getInstance()));
//        params.put("page", 1);
//        params.put("toUserId", toUserId);
//        showProgress(getClass().getSimpleName());
//        Call<ApiResponseBody> call = apiservice.addDiscuss(params);
//        call.enqueue(new Callback<ApiResponseBody>() {
//            @Override
//            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
//                dismissProgress();
//                if (response.isSuccessful()) {
//                    showTost("提交成功", 0);
//                    commit.setVisibility(View.GONE);
//                    getBaseActivity().hideSoftKeybord();
//                    toUserName.setText("");
//                    etComment.setText("");
//                    selAnswerDetail();
//                } else {
//                    showTost(response.raw().message(), 1);
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
//                dismissProgress();
//                ApiException apiException = ExceptionHandle.handleException(t);
//                if (apiException.isTokenInvalid()) {
//                    showUnLoginSnackbar();
//                } else if (apiException.isNetConnected()) {
//                    showSetNetworkSnackbar();
//                } else {
//                    showTost(apiException.getMessage(), 0);
//                }
//            }
//        });
//    }

    //点赞接口
    private void dealZan(String id, String temp, final int type) {
        if (Util.isEmpty(PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID))) {
            showTost("未登录，不能点赞！请先登录", 1);
            return;
        }
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("temp", temp);
        params.put("type", type);
        params.put("id", id);
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
//        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.doLike(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    if(type==4){
                        int number = TextUtils.isEmpty(tvTotalZan.getText().toString())?0:Integer.valueOf(tvTotalZan.getText().toString());
                        if (zanTemp.equals("1")) {
                            number++;
                            zanTemp = "0";
                            tvZan.setImageResource(R.mipmap.zan_1);
                            ivZan.setImageResource(R.mipmap.zan_1);
                        } else {
                            number--;
                            tvZan.setImageResource(R.mipmap.zan_2);
                            ivZan .setImageResource(R.mipmap.zan_2);
                            zanTemp = "1";
                        }
                        tvTotalZan.setText(String.valueOf(number));
                    }
                    selAnswerDetail();
                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException exception = ExceptionHandle.handleException(t);
                if (exception.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (exception.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(exception.getMessage(), 1);
                }
            }
        });

    }

}
